
import dao from '@/dao';
// 空函数
const noop = function() {};

let codeHandlers = {};

/**
 * 注册请求状态码处理函数
 * @param {Object} handlers 
 * {
 *    20100001: function(res, payload){},
 *    40000002: function(res, payload){}
 * }
 */
function useCodeHandlers(handlers) {
    codeHandlers = handlers || {};
}

function getHandlerByCode(code) {
    return codeHandlers[code] || noop;
}
function getMessageHandler() {
    return codeHandlers.message || noop;
}

function tx(payload, callback) {
    const messageHandler = getMessageHandler();
    return new Promise((resolve, reject) => {
        dao.x(payload).then((res) => {
            // let { status } = res;
            // let { code } = status;
            let code = res.code || res.status?.code || res.status;
            getHandlerByCode(code)(res, payload);
            messageHandler(res, payload);
            // 状态码为 200 时走resolve, 其他情况都走reject
            if(code == 200) {
                resolve(res);
            } else {
                reject(res);
            }
        }).catch(error => {
            messageHandler({
                code: -1,
                error
            }, payload);
        });
    });
}

export {
    tx,
    useCodeHandlers
}
